
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/2/25 21:50
# @Author  : jize.liu
# @File    : Maya_BatchOutput.py
# @声明     : 版权由 刘继泽 所有,如有疑问，需要帮助请联系刘继泽
import os, subprocess, sys, winreg
import pandas as pd
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QCheckBox, QVBoxLayout, QSplitter
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from Batch_Submission_ui import Ui_Batch_Submission_Win
from PySide6.QtCore import QThread, Signal, QObject


class FileProcessor (QThread) :
    progressChanged = Signal (int)  # 定义一个进度信号

    def __init__(self, FliePath, Check, current_folder, file_list, maya_version) :
        super ().__init__ ()
        self.Check = Check
        self.FliePath = FliePath
        self.current_folder = current_folder
        self.file_list = file_list
        self.maya_version = maya_version

    def run(self) :
        command_script = os.path.join (self.current_folder, "myPlayBlast.py").replace ("\\", "/")
        imp_path_script = os.path.join (self.current_folder, "imp_path.py").replace ("\\", "/")
        '''
        CheckList = os.path.join ( self.current_folder , "CheckInformation.txt" ).replace ( "\\" , "/" )
        Check = ''
        with open (CheckList, "r" ) as file :
            content = file.read ( )
            all_txt = content.split ( "\n" )
            for i in all_txt :
                link = i.split ( ",,," )
                Check += link [ 1 ] + ","
        '''
        for i, ma_file in enumerate (self.file_list) :
            ## python方法
            output_folder = os.path.dirname (ma_file)
            #cmd = self.maya_version + " -command " + melFile + " " + self.Check + " " + publishPath + " " + maPath + " " + currentFolder
            #print(cmd)
            #subprocess.check_call (cmd)
            command=[]
            version_info = sys.version_info
            if version_info.major == 2 :
                command = [self.maya_version , "-command" , "python(\"execfile('{}')\")".format (imp_path_script) , self.Check , command_script , ma_file , output_folder]

            elif version_info.major == 3 :
                command = [self.maya_version , "-command" , "python(\"exec(open('{}').read())\")".format (imp_path_script) , self.Check  , command_script , ma_file , output_folder]
            """
            maya_path = r"C:/Program Files/Autodesk/Maya2023/bin/mayabatch.exe"  # 替换为您的 Maya 安装路径
            imp_path_script = r"J:/TeamSavior/Win/Batch_Submission_V2/imp_path.py"
            command_script = r"J:/TeamSavior/Win/Batch_Submission_V2/myPlayBlast.py"
            ma_file = r"C:/Users/jize.liu/Desktop/F38/F38_SC001.ma"
            output_folder = r"C:/Users/jize.liu/Desktop/F38"

            command = [maya_path , "-command" , "python(\"exec(open('{}').read())\")".format (imp_path_script) , "Check_Export_Cam_FBX" , command_script , ma_file , output_folder]
            """
            subprocess.check_call (command)

            ## Mel方法  #
            #cmd = '"{mayaBatchPath}" -script "{melFile}" "{newFile}" "{publishPath}" "{maPath}" "{currentFolder}"'.format ( mayaBatchPath = MAYABATCHPATH , melFile = melFile , newFile = newFile , publishPath = publishPath , maPath = ii , currentFolder = os.path.dirname ( ii ) ,)  # subprocess.check_call ( cmd , shell = True )
            #subprocess.check_call ( cmd , shell = True )
            # 发出进度信号
            self.progressChanged.emit (i + 1)
        try :
            logPath = os.path.join (self.FliePath, "log")
            TxT_Log_Name = "log.txt"
            xlsx_Log_Name = "log.xlsx"
            TxT_Log = os.path.join (logPath, TxT_Log_Name).replace ('\\', '/')
            xlsx_Log = os.path.join (logPath, xlsx_Log_Name).replace ('\\', '/')
            file_name, file_extension = os.path.splitext (TxT_Log)
            if file_extension == ".txt" :
                # 读取文本文件
                with open (TxT_Log, 'r', encoding='utf-8', errors='ignore') as file :
                    lines = file.readlines ()
                # 拆分字段并创建 DataFrame
                data = []
                for line in lines :
                    parts = line.strip ().split (',')
                    data.append (parts)
                max_length = max (len (row) for row in data)
                columns = []
                for i in range (1, max_length + 1) :
                    columns.append ("Column" + str (i))
                # 创建 DataFrame
                df = pd.DataFrame (data, columns=columns)
                # 创建 Excel writer 对象
                with pd.ExcelWriter (xlsx_Log, engine='openpyxl') as writer :
                    # 将数据写入 Excel 表格
                    df.to_excel (writer, index=False, sheet_name='Sheet1')
            # 读取 Excel 文件
            wb = load_workbook (xlsx_Log)
            # 选择工作表
            ws = wb['Sheet1']
            # 设置单元格样式
            green_fill = PatternFill (fill_type='solid', fgColor='00FF00')
            red_fill = PatternFill (fill_type='solid', fgColor='FF0000')
            # 遍历单元格并设置颜色
            for row in ws.iter_rows () :
                for cell in row :
                    if cell.value and 'YES' in str (cell.value) :
                        cell.fill = green_fill
                    if cell.value and 'NO' in str (cell.value) :
                        cell.fill = red_fill

            # 保存修改
            wb.save (xlsx_Log)
        except :
            pass


class PIliangtijiao (Ui_Batch_Submission_Win, QMainWindow) :
    def __init__(self) :
        super (PIliangtijiao, self).__init__ ()
        self.setupUi (self)
        self.__ui__ ()
        self.process_thread = None

    def __ui__(self) :
        # 获取当前文件所在的文件夹路径
        self.current_folder = os.path.dirname (os.path.abspath (__file__))
        os.environ['PYTHONPATH'] = os.path.join (self.current_folder, "CheckType")
        self.Check_List ()
        self.combobox ()
        self.pushButton.clicked.connect (self.select_folder)
        self.pushButton_3.clicked.connect (self.start_processing)
        self.MayaVersion.currentIndexChanged.connect (lambda *args : self.get_selected_option ())

    def Check_List(self) :

        checkBoxList = self.scrollAreaWidgetContents.findChildren (QVBoxLayout)[0]
        CheckList = os.path.join (self.current_folder, "CheckInformation.txt").replace ("\\", "/")
        Check = ''
        with open (CheckList, "r") as file :
            content = file.read ()
            all_txt = content.split ("\n")
            for i in all_txt :
                self.link = i.split (",,,")
                print (self.link)
                Check += self.link[1] + ","
                checkbox = QCheckBox (self.link[0])
                checkBoxList.addWidget (checkbox)
        splitter = QSplitter ()
        splitter.setObjectName ("splitter")
        checkBoxList.addWidget (splitter)
        self.isChecked_List ()

    def isChecked_List(self) :
        self.Check = ''
        checkBoxList = self.scrollAreaWidgetContents.findChildren (QCheckBox)
        for checkBox in checkBoxList :
            if checkBox.text () != "全选/未选" :
                CheckList = os.path.join (self.current_folder, "CheckInformation.txt").replace ("\\", "/")
                with open (CheckList, "r") as file :
                    content = file.read ()
                    all_txt = content.split ("\n")
                    for i in all_txt :
                        self.link = i.split (",,,")
                        if checkBox.isChecked () :
                            if checkBox.text () == self.link[0] :
                                self.Check += self.link[1] + ","
        return (self.Check)

    def start_processing(self) :
        self.isChecked_List ()
        file_list = []
        self.progressBar.setValue (0)
        file_count = self.Flie_listWidget.count ()
        self.progressBar.setMaximum (file_count)
        selected_option = self.get_selected_option ()
        for i in range (self.Flie_listWidget.count ()) :
            item = self.Flie_listWidget.item (i)
            file_list.append (item.text ())
        self.thread = FileProcessor (self.lineEdit.text (), self.isChecked_List (), self.current_folder, file_list, self.Set_MayaVersion ().get (selected_option))
        self.thread.progressChanged.connect (self.update_progress)  # 连接进度信号与更新进度条的方法
        self.thread.start ()

    def update_progress(self, value) :
        self.progressBar.setValue (value)  # 更新进度条的值

    def combobox(self) :
        items = (list (self.Set_MayaVersion ().keys ()))
        self.MayaVersion.addItems (items)

    def get_selected_option(self) :
        selected_option = self.MayaVersion.currentText ()
        return (selected_option)

    def select_folder(self) :
        folder_path = QFileDialog.getExistingDirectory (self, "选择文件夹")
        if len (folder_path) :
            self.lineEdit.setText (folder_path)
            self.Flie_listWidget.clear ()
            file_type = ['ma', 'mb']
            for file_name in os.listdir (folder_path) :
                # 过滤文件夹，只添加文件
                if os.path.isfile (os.path.join (folder_path, file_name)) :
                    file_path = os.path.join (folder_path, file_name)
                    file_path = file_path.replace ('\\', '/')
                    if file_path.rsplit ('.', 1)[-1] in file_type :
                        # 将文件名添加到列表控件
                        self.Flie_listWidget.addItem (file_path)

    def Set_MayaVersion(self) :
        my_maya = {}
        for i in range (2008, 2025) :
            try :
                key = winreg.OpenKey (winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Autodesk\\Maya' + '\\' + str (i) + '\\' + 'Setup\\InstallPath')
                path = winreg.QueryValueEx (key, 'MAYA_INSTALL_LOCATION')
                if path[0] :
                    mayabatch = os.path.join (os.path.join (path[0], "bin"), "mayabatch.exe")
                    my_maya[str (i)] = mayabatch.replace ('\\', '/')
            except :
                pass
        return (my_maya)


if __name__ == '__main__' :
    app = QApplication (sys.argv)
    window = PIliangtijiao ()
    window.show ()
    sys.exit (app.exec ())
